package pers.ree.demo.io.nio;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

    public static void main(String[] args) {
        try {
//            RandomAccessFile file = new RandomAccessFile("/Users/rui/Downloads/开课吧/mysql/2020.11.27作业.txt", "rw");
            RandomAccessFile file = new RandomAccessFile("/Users/rui/Downloads/开课吧/mysql/nio-test.txt", "rw");

            FileChannel channel = file.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(48);

            int bytesRead = channel.read(buffer);

            while (bytesRead != -1) {
                System.out.println("bytesRead:" + bytesRead);
                buffer.flip();

                while(buffer.hasRemaining()){
                    System.out.print((char) buffer.get());
                }

                buffer.clear();
                bytesRead = channel.read(buffer);
            }

            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void transferTest() {
        try {
            RandomAccessFile fromFile = new RandomAccessFile("/Users/rui/demo/test_data/nio-from-test.txt", "rw");
            FileChannel fromChannel = fromFile.getChannel();

            RandomAccessFile toFile = new RandomAccessFile("/Users/rui/demo/test_data/nio-to-test.txt", "rw");
            FileChannel toChannel = toFile.getChannel();

            long position = 0L;
            long count = fromChannel.size();

            System.out.println(count);

            toChannel.transferFrom(fromChannel, position, count);

            RandomAccessFile toFile2 = new RandomAccessFile("/Users/rui/demo/test_data/nio-to-test2.txt", "rw");
            FileChannel toChannel2 = toFile2.getChannel();
            fromChannel.transferTo(position, count, toChannel2);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
